<template>
  <div>
    <van-cell-group border>
      <van-field
        v-model="yzm"
        label="验证码"
        placeholder="请输入手机号..."
        autofocus
      >
        <template #button>
          <van-button
            size="small"
            :disabled="btnFlag"
            type="primary"
            @click="sendMsg"
            >{{ txt }}</van-button
          >
        </template>
      </van-field>
    </van-cell-group>
    <div class="loginBtn">
      <van-button type="danger" round block :disabled="flag" @click="next"
        >下一步</van-button
      >
    </div>
  </div>
</template>

<script>
import { doSendMsg, doCheckCode } from "../../api/user";
import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);
export default {
  data() {
    return {
      yzm: "",
      txt: "发送验证码",
      time: 60,
      btnFlag: false,
    };
  },
  methods: {
    sendMsg() {
      const timer = setInterval(() => {
        this.time--;
        if (this.time == 0) {
          clearInterval(timer);
          this.btnFlag = false;
          this.txt = "发送验证码";
          this.time = 60;
        } else {
          this.txt = this.time + "s后发送验证码";
          this.btnFlag = true;
        }
      }, 1000);

      setTimeout(() => {
        doSendMsg({ tel: localStorage.getItem("tel") }).then((res) => {
          console.log(res.data.data);
          this.yzm = res.data.data;
        });
      }, 1500);
    },
    next() {
      // 验证验证码
      doCheckCode({tel:localStorage.getItem('tel'),telcode:this.yzm}).then(res=>{
         console.log(res.data.code);

         switch (res.data.code) {
            case '10007':
                Toast('验证码有误,请重新输入');
                break;
             case '200':
                this.$router.push('/register/three')
                break;
            default:
                break;
         }
      })
    },
  },
  computed: {
    flag() {
      if (/^\d{5}$/.test(this.yzm)) {
        return false; //红色
      } else {
        return true; //  灰色禁用
      }
    },
  },
};
</script>

<style scoped>
.loginBtn {
  width: 80%;
  margin: 20px auto;
}
</style>